// D3D9IndexBuffer.cpp

#include "stdafx.h"

#include "..\Core\core.h"

#include "D3D9IndexBuffer.h"

//////////////////////////////////////////////////////////////////////////
CD3D9IndexBuffer::CD3D9IndexBuffer(D3DFORMAT indexType, size_t numIndices, DWORD dwUsage, LPDIRECT3DDEVICE9 pDev)
{
	// Calculate the size of the indexes
	size_t nIndexSize = 0;
	switch (indexType)
	{
	case D3DFMT_INDEX16:
		nIndexSize = sizeof(unsigned short);
		break;
	case D3DFMT_INDEX32:
		nIndexSize = sizeof(unsigned int);
		break;
	}
	size_t SizeInBytes = nIndexSize * numIndices;

	HRESULT hr = pDev->CreateIndexBuffer(static_cast<UINT>(SizeInBytes), 
		dwUsage, 
		indexType, 
		D3DPOOL_DEFAULT,
		&m_pIndexBuffer,
		NULL);

	if (FAILED(hr))
	{
		// msg failed to create index buffer.
	}
}

CD3D9IndexBuffer::~CD3D9IndexBuffer()
{
	SAFE_RELEASE(m_pIndexBuffer);
}

//////////////////////////////////////////////////////////////////////////
IDirect3DIndexBuffer9* CD3D9IndexBuffer::GetBuffer(void) const
{
	return m_pIndexBuffer;
}

//////////////////////////////////////////////////////////////////////////
void CD3D9IndexBuffer::write(size_t offset, size_t length, const void *pSource, bool bDiscardWholeBuffer)
{
	void* pDst = NULL;
	HRESULT hr = m_pIndexBuffer->Lock(static_cast<UINT>(offset),
		static_cast<UINT>(length),
		&pDst,
		D3DLOCK_DISCARD);

	if (FAILED(hr))
	{
		return;
	}

	memcpy(pDst, pSource, length);
	m_pIndexBuffer->Unlock();
}